//


#import "MB_FirstViewController.h"
#import "MB_SearchHeaderView.h"
#import "MB_FirstTableViewCell.h"
#import "MB_AddViewController.h"
#import "MB_DetailsViewController.h"
#import "MB_PersonalViewController.h"

@interface MB_FirstViewController ()<UITableViewDelegate,UITableViewDataSource,MB_SearchHeaderDelegate>
/** */
@property (nonatomic, strong) UITableView *firstTableView;
/** */
@property (nonatomic, strong) NSMutableArray *dataArr;
/** */
@property (nonatomic, strong) NSMutableArray *addArray;
/** */
@property (nonatomic, strong) MB_SqlView *sql;
/** 是否弹出添加页面*/
@property (nonatomic, assign) BOOL  isShow;

@end

@implementation MB_FirstViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    self.navigationController.navigationBarHidden = YES;
    _sql = [[MB_SqlView alloc]initWithData:@"FirstData" dataName:@"MoodData" success:^{} fail:^(NSError * _Nullable error) {}];
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"isget" ]) {
        //        [self savedefault];
    }
    [self getfirestData];
}
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBarHidden = NO;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setNavItem];
    [self setSearchBar];
    [self.view addSubview:self.firstTableView];
    
}

//#pragma mark ----------------- tableViewDelegate ----------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cellIdentifier";
    MB_FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[MB_FirstTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = _dataArr[indexPath.section];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kRHeight(10);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}
//*
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    FirstData *moel = _dataArr[indexPath.section];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //
        [_sql mb_deleteEntity:nil key:[NSString stringWithFormat:@"id=%@",moel.id] success:^{[self getfirestData];} fail:^(NSError * _Nullable error) {}];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"Delete";
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MB_DetailsViewController *vc = [[MB_DetailsViewController alloc]init];
    vc.model = _dataArr[indexPath.section];
    [self.navigationController pushViewController:vc animated:YES];
}
//*/
//
- (void)setNavItem {
    //
    [self setnavBatalweeTitle:@"Main"];
    __weak typeof(self) weakSelf = self;
    [self setupLeftyqwnvjqAndRightSetting:[UIImage imageNamed:@"Add"] block:^{
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:[MB_AddViewController alloc]];
        [weakSelf presentViewController:nav animated:YES completion:nil];
    }];
    //
//    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 25)];
//    [button setTitle:@"Personal" forState:UIControlStateNormal];
//    [button setTitleColor:RGBA(51, 51, 51, 1) forState:UIControlStateNormal];
//    [button.titleLabel setFont:FontPFRegular(kRWidth(15))];
//    [button addTarget:self action:@selector(ActionBack) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:button];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
}
- (void)ActionBack {
    MB_PersonalViewController *vc = [[MB_PersonalViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

//MARK:sousuo
- (void)setSearchBar {
    MB_SearchHeaderView *bar = [[MB_SearchHeaderView alloc]initWithFrame:CGRectMake(0, 0, kMainScreenWidth, kRHeight(40))];
    bar.backgroundColor = RGB(232, 232 ,232);
    bar.delegate = self;
    [self.view addSubview:bar];
    
}
- (void)textFieldChange:(NSString *)text {
    
    if (text.length <= 0) {
        [self getfirestData];
        return;
    }
    [_sql mb_readEntity:nil ascending:NO filterStr:[NSString stringWithFormat:@"content CONTAINS[cd]'%@'",text] success:^(NSArray * _Nonnull results) {
        if(!results)return ;
        
        self.dataArr = [results copy];
        [self.firstTableView reloadData];
    } fail:^(NSError * _Nullable error) {}];
}

//
#pragma mark ----------------- mark ----------------
- (UITableView *)firstTableView {
    if (!_firstTableView) {
        _firstTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kRHeight(40), kMainScreenWidth, kMainScreenHeight - kRHeight(40) - UI_NAV_BAR_HEIGHT) style:UITableViewStylePlain];
        _firstTableView.dataSource = self;
        _firstTableView.delegate   = self;
        _firstTableView.separatorColor = [UIColor whiteColor];
        _firstTableView.tableFooterView = [UIView new];
        _firstTableView.rowHeight = UITableViewAutomaticDimension;
        _firstTableView.estimatedRowHeight = kRHeight(70);
        
    }
    return _firstTableView;
}
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}
- (NSMutableArray *)addArray {
    if (!_addArray) {
        _addArray = [NSMutableArray arrayWithObjects:@{@"id":@"1",@"date":@"05-31 11:23",@"content":@"Xi, also Chinese president, chairman of the Central Military Commission, and head of the central committee for deepening overall reform, called for further reform to better serve the overall economic and social development"}, @{@"id":@"2",@"date":@"06-02 11:23",@"content":@"Maba Men were found living here as early as 129,000 years ago, who turned over the first page of the Guangdong social history as the earliest human beings ever found here. As the legend goes, the ethnic Yue people resided here in ancient times"},@{@"id":@"3",@"date":@"06-01 11:23",@"content":@"eign of Qin Shihuang in the Qin Dynasty, Qin Shihuang, the first emperor of China, sent his loyal army led by General Tu Sui to conquer Lingnan Region. Three shires "},@{@"id":@"4",@"date":@"06-02 11:23",@"content":@" the first prefectural commissioner of Naihai Shire, constructed a walled city at Panyu, which was also called Renxiao Town or Qincheng Town. Panyu Town in history is regarded as the starting point where Guangzhou developed into a big city."},@{@"id":@"5",@"date":@"06-01 11:23",@"content":@"First Year of the First Emperor of the Han Dynasty. When Zhao Tuo became the successor of the prefectural commissioner of Nanhai, he made himself king of Nanyue Kingdom entitled King Wuwang with Panyu the capital for the first time in history"},nil];
    }
    return _addArray;
}

- (void)getfirestData{
    
    [_sql mb_readEntity:@[@"date"] ascending:NO filterStr:nil success:^(NSArray * _Nonnull results) {
        if(!results)return ;
        
        self.dataArr = [results copy];
        [self.firstTableView reloadData];
        
        if (self.dataArr.count <= 0 && !self.isShow) {
            self.isShow = YES;
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:[MB_AddViewController alloc]];
            [self presentViewController:nav animated:YES completion:nil];
        }
        
    } fail:^(NSError * _Nullable error) {}];
}
- (void)savedefault {
    
    [[NSUserDefaults standardUserDefaults]setObject:@"s" forKey:@"isget"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    for (NSDictionary *dic in self.addArray) {
        [_sql mb_insertNewEntity:dic success:^{} fail:^(NSError * _Nullable error) {}];
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (BOOL)bm_isShowLeftswqrrSetting {
    return NO;
}

@end
